import { ITouchEvent } from "@tarojs/components"
import { useState, MutableRefObject, useRef, useEffect } from "react"

/**
 * 自定义播放按钮通用逻辑
 */
export function useCustomPlayState(
  videoContextRef: MutableRefObject<Taro.VideoContext | null | undefined>
) {
  /** 视频是否播放 */
  const videoPlaying = useRef<boolean>(false)
  const [showPlayBtn, setShowPlayBtn] = useState(true)
  /** 当播放时 */
  function handlePlay() {
    setShowPlayBtn(false)
    videoPlaying.current = true
  }
  /** 当暂停播放时 */
  function handlePause() {
    setShowPlayBtn(true)
    videoPlaying.current = false
  }
  /** 当结束播放时 */
  function handleEnded() {
    setShowPlayBtn(true)
    videoPlaying.current = false
  }
  /** 当点击播放按钮时 */
  function handleClickPlayBtn(ev: ITouchEvent) {
    if (videoContextRef.current) {
      ev.preventDefault()
      ev.stopPropagation()
      videoContextRef.current.play()
      setShowPlayBtn(false)
    }
  }
  return {
    videoPlaying,
    showPlayBtn,
    handlePlay,
    handlePause,
    handleEnded,
    handleClickPlayBtn
  }
}
/**
 * 历经duration`s`后触发指定方法
 * @param handler 触发指定方法
 * @param duration 时长, 单位`s`
 * @param cancelState 该状态为真时取消
 */
export function useTimedown(handler: IFn, duration: number, cancelState: boolean) {
  const current = useRef<number>(0)
  const timer = useRef<any>()
  useEffect(() => {
    timer.current = setTimeout(() => {
      handler()
    }, 1000 * duration)
    return cancel
  }, [])
  useEffect(() => {
    if (cancelState && typeof timer.current !== "undefined") {
      cancel()
    }
  }, [cancelState])
  function cancel() {
    clearTimeout(timer.current)
    timer.current = void 0
    current.current = 0
  }
}
